<template>
    <div class="container">
        <el-row>
            <el-card shadow="never">
                <div slot="header">
                    <el-form :inline="true" :model="searchForm" size="small">
                        <el-form-item label="名称" class="el-search-item">
                            <el-input v-model="searchForm.name" placeholder="角色名称" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="创建时间" class="el-search-item">
                            <el-date-picker
                                v-model="checkedTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button type="success" plain icon="el-icon-search" @click="getDataList()">查询</el-button>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button v-if='hasPerm("sys:role:add")' type="primary" plain icon="el-icon-plus" @click="openAdd">新增角色</el-button>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button type="info" plain icon="el-icon-folder-opened">导入角色</el-button>
                        </el-form-item>
                        <el-form-item class="el-search-item">
                            <el-button type="danger" plain icon="el-icon-printer">导出角色</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <!--数据表格 element ui-->
                <el-table :data="tableData" :height="tableHeight" style="width: 100%">
                    <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
                    <el-table-column prop="name" label="名称" align="center" sortable></el-table-column>
                    <el-table-column prop="remark" label="备注" align="center" sortable></el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center" sortable></el-table-column>
                    <el-table-column prop="updateTime" label="更新时间" align="center" sortable></el-table-column>
                    <el-table-column v-if='hasPerm("sys:role:update") || hasPerm("sys:role:assign") || hasPerm("sys:role:del")' label="更多操作" align="center" width="250">
                        <template slot-scope="scope">
                            <el-button v-if='hasPerm("sys:role:update")' @click="openUpdate(scope.row)" size="mini" type="text" icon="el-icon-edit">编辑</el-button>
                            <el-button v-if='hasPerm("sys:role:assign")' @click="showAssignDialog(scope.row)" size="mini" type="text" icon="el-icon-unlock">权限配置</el-button>
                            <el-button v-if='hasPerm("sys:role:del")' @click="deleteFun(scope.row)" size="mini" type="text" icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!--新增角色对话框-->
                <el-dialog :title="dialog.dialogTitle" :visible.sync="dialog.visible" width="35%">
                    <el-form :rules="rules" ref="roleForm" :model="roleForm" size="small" label-width="80px">
                        <el-form-item prop="name" label="角色名称">
                            <el-input v-model="roleForm.name" placeholder="请输入角色名称" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item prop="remark" label="角色描述">
                            <el-input v-model="roleForm.remark" placeholder="请输入角色描述" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialog.visible = false" size="small">取 消</el-button>
                        <el-button type="primary" @click="submitFun()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
                    </span>
                </el-dialog>

                <!-- 分配权限对话框-->
                <el-dialog class="self_dialog" :title="menuDialog.dialogTitle" :visible.sync="menuDialog.visible" width="26%" top="5%">
                    <el-tree :data="treeData"
                             :props="treeProps"
                             show-checkbox
                             node-key="id"
                             default-expand-all
                             :default-checked-keys="defKeys"
                             ref="treeRef"
                             style="height: 55vh;overflow: auto;"
                    ></el-tree>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="menuDialog.visible = false" size="small">取 消</el-button>
                        <el-button type="primary" @click="saveRoleMenuFun()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
                    </span>
                </el-dialog>
            </el-card>
        </el-row>
    </div>
</template>

<script>
export default {//vue3
    data() {
        return {
            // 表格数据
            tableData: [],
            // 表格高度
            tableHeight: 0,
            // 用来存放日期组件所选中的值
            checkedTime: '',
            // 查询参数
            searchForm: {
                name: null,
                startTime: null,
                endTime: null,
            },
            // 弹出层
            dialog: {
                flag: 0,
                dialogTitle: "",
                visible: false
            },
            // 菜单弹出层
            menuDialog: {
                dialogTitle: "",
                visible: false
            },
            // 表单参数
            roleForm: {
                id: null,
                name: null,
                remark: null
            },
            // 提交按钮文字
            loading: {
                status: false,
                BtnText: '确 定',
                SubText: '提交中...',
            },
            // 表单校验
            rules: {
                name: [{required: true, trigger: "change",  message: "请输入角色名称"}],
                remark: [{required: true, trigger: "change",  message: "请输入角色备注"}]
            },
            // 所有权限数据
            treeData: [],
            // 树形控件的属性绑定对象
            treeProps: {
                children: 'children',
                label: 'label'
            },
            // 默认选中的节点id值
            defKeys: [],
            // 角色id
            roleId: null
        };
    },
    mounted() {
        this.$nextTick(() => {
            this.tableHeight = window.innerHeight - 205;
        });
    },
    created() {
        this.getDataList()
    },
    watch: {
        "checkedTime"(value) {
            this.searchForm.startTime = null
            this.searchForm.endTime = null
            if (value != null) {
                let timeArr = value.toString().split(",")
                timeArr.forEach((item,i) => {
                    if(i === 0) {
                        this.searchForm.startTime = item
                    }else {
                        this.searchForm.endTime = item
                    }
                })
            }
        }
    },
    methods: {
        // 获取角色权限列表
        getDataList() {
            this.$api.role.list({
                name: this.searchForm.name,
                startTime: this.searchForm.startTime,
                endTime: this.searchForm.endTime
            }).then(res => {
                if(res.data.code === 2000) {
                    this.tableData = res.data.data
                }
            })
        },
        // 新增按钮操作
        openAdd() {
            this.dialog.flag = 0
            this.resetForm("roleForm")
            this.dialog.dialogTitle = "新增角色"
            this.dialog.visible = true
        },
        // 更新按钮操作
        openUpdate(row) {
            this.dialog.flag = 1
            this.resetForm("roleForm")
            this.dialog.dialogTitle = "编辑角色"
            this.dialog.visible = true
            this.getById(row.id)
        },
        // 提交数据操作
        submitFun() {
            this.$refs.roleForm.validate(valid => {
                if(valid){
                    this.loading.status = true
                    this.$api.role.saveOrUpdate(this.roleForm,this.dialog.flag).then(res => {
                        if (res.data.code === 2000) {
                            this.$message.success(res.data.msg)
                            this.getDataList()
                            // 关闭弹框
                            this.dialog.visible = false
                            // 关闭加载
                            this.loading.status = false
                        }else{
                            this.$message.error(res.data.msg)
                            this.loading.status = false
                            return false
                        }
                    })
                }
            })
        },
        // 根据id获取信息
        getById(id) {
            this.$api.role.getById(id).then(res => {
                if (res.data.code === 2000) {
                    this.roleForm.id = res.data.data.id;
                    this.roleForm.name = res.data.data.name;
                    this.roleForm.remark = res.data.data.remark;
                }
            })
        },
        // 展示分配权限对话框
        showAssignDialog(row) {
            this.getTreeData()
            this.roleId = row.id
            // 递归获取三级节点id
            this.defKeys = []
            this.getLeafKeys(row,this.defKeys)
            this.menuDialog.dialogTitle = '【' + row.name + '】分配权限'
            this.menuDialog.visible = true
        },
        // 获取所有权限数据
        getTreeData() {
          this.$api.menu.list().then(res => {
              if(res.data.code === 2000) {
                  this.treeData = res.data.data;
              }
          })
        },
        // 通过递归的形式获取角色下所有权限id
        getLeafKeys(node,arr) {
            if(node.children.length === 0) {
                return arr.push(node.id)
            }
            node.children.forEach(item => this.getLeafKeys(item,arr))
        },
        // 为角色分配权限
        saveRoleMenuFun() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            if (keys.length === 0) {
                this.$message.error("请选择需要配置的权限节点！");
                return false;
            }
            this.loading.status = true
            this.$api.menu.saveRoleMenu({
                roleId: this.roleId,
                ids: keys
            }).then(res => {
                if (res.data.code === 2000) {
                    this.$message.success(res.data.msg)
                    this.menuDialog.visible = false
                    this.loading.status = false
                    this.getDataList()
                }else {
                    this.$message.error(res.data.msg)
                    this.menuDialog.visible = false
                    this.loading.status = false
                    return false
                }
            })
        },
        // 根据id删除角色
        deleteFun(row) {
            this.$confirm("确定删除当前角色吗？", "系统提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: 'error'
            }).then(() =>{
                this.$api.role.remove(row.id).then(res => {
                    if(res.data.code === 2000){
                        this.$message.success(res.data.msg)
                        this.getDataList()
                    }else {
                        this.$message.error(res.data.msg)
                    }
                })
            }).catch(() => {
                this.$message.info("取消删除")
            });
        },
        // 清空表单
        resetForm(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].resetFields();
            }
        },
    }
}
</script>

<style lang="less" scoped>
.el-search-item {
    margin-bottom: 0;
}
.el-card/deep/.el-card__body {
    padding: 0 10px 10px 10px !important;
}
.el-card/deep/.el-card__header {
    border-bottom: none !important;
}

</style>
